package com.example.asuper.check;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.Layout;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asuper.check.Db.CheckDAL;
import com.example.asuper.check.Helper.OperateType;
import com.example.asuper.check.Helper.ConvertHelper;
import com.example.asuper.check.Helper.SharePrefenceHelper;
import com.example.asuper.check.Model.CheckModel;
import com.example.asuper.check.Model.TitleMessageModel;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class ScanCodeAndCheckActivity extends Activity implements View.OnClickListener, View.OnTouchListener {
    //private ListView mListView;
    private EditText edShowCodeResult;
    private EditText edRemark;
    private TextView tvShowResultDetail;
    private ImageButton imbtSacnCode;
    private ImageButton imbtChecking;
    private LinearLayout lyResult;
    private ArrayList<CheckModel> mCheckModels;
    private CheckDAL checkDbService;
    private Button btnSearch;
    private CheckBox cbQuickCheck;
    //    private Button btnCancel;
    private VelocityTracker mVeloctity;
    private TextView tvScanResultLast;
    private TextView tvTitleChecked;
    private TextView tvTitleUncheck;
    private TextView tvTitleOverage;
    private TextView tvTitleBack;

    private String SpliteCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scancodeandcheck);
        //mListView = (ListView) findViewById(R.id.lv_all_list);
        // mCheckModels=CheckModelLab.get(ScanCodeAndCheckActivity.this).getCheckModels();
        //ArrayAdapter<CheckModel> arrayAdapter=new ArrayAdapter<CheckModel>(this,android.R.layout.simple_list_item_1,mCheckModels);
        //mListView.setAdapter(arrayAdapter);
        this.setTitle("扫描与盘点");
        edShowCodeResult = (EditText) findViewById(R.id.edt_coderesult);
        tvShowResultDetail = (TextView) findViewById(R.id.tv_coderesultdetail);
        imbtSacnCode = (ImageButton) findViewById(R.id.imgbtn_scancode);
        imbtChecking = (ImageButton) findViewById(R.id.imgbtn_submitcheck);
        btnSearch = (Button) findViewById(R.id.btn_search_scancheck);
//        btnCancel=(Button)findViewById(R.id.btn_cancel_scancheck);
        tvScanResultLast = (TextView) findViewById(R.id.scanResultLast);
        tvTitleChecked = (TextView) findViewById(R.id.application_tv_showChecked);
        tvTitleUncheck = (TextView) findViewById(R.id.application_tv_showUncheck);
        tvTitleOverage = (TextView) findViewById(R.id.application_tv_showOverage);
        tvTitleBack = (TextView) findViewById(R.id.application_tv_titleback);
        edRemark = (EditText) findViewById(R.id.ed_scanAndCheck_remark);
        lyResult = (LinearLayout) findViewById(R.id.ly_scanAndCheck_result);
        cbQuickCheck = (CheckBox) findViewById(R.id.cb_scanAndcheck_quickcheck);
        imbtSacnCode.setOnClickListener(this);
        imbtChecking.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
//        btnCancel.setOnClickListener(this);
        tvTitleBack.setOnClickListener(this);
        SpliteCode = SharePrefenceHelper.ReadSharedPreferences("splite_info", "SPLITE", this);
        final View thisLayout = findViewById(R.id.scancodeandcheck_layout_main);
        //thisLayout.setOnTouchListener(this);
        thisLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //比较Activity根布局与当前布局的大小
                int heightDiff = thisLayout.getRootView().getHeight() - thisLayout.getHeight();
                if (heightDiff > 100) {
                    //大小超过100时，一般为显示虚拟键盘事件
                    setLayoutResultMin();
                } else {
                    //大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
                    setLayoutResultMax();
                }

            }
        });
        edShowCodeResult.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    searchAndEnterKey();
                    return true;
                }
                return false;
            }
        });
        initTitleMsg();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgbtn_scancode:
                tvShowResultDetail.setText("");
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.btn_search_scancheck:
                searchAndEnterKey();
                break;
//            case  R.id.btn_cancel_scancheck:
//                cancelAll();
//                break;
            case R.id.imgbtn_submitcheck:
                checkdate();
                updateDate();
                break;
            case R.id.application_tv_titleback:
                finish();
                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            String result = data.getStringExtra("result");
            tvScanResultLast.setText(result);
            updateDate();
            //如果勾选快速盘点，那么回车事件在查询以后，直接盘点
            if (cbQuickCheck.isChecked()){
                checkdate();
                updateDate();
            }
        }
    }

    //盘点
    private boolean checkdate() {
        boolean result = false;
        String codeResult = tvScanResultLast.getText().toString().trim();
        if (codeResult.equals("")) {
            Toast.makeText(this, "条码不能为空！", Toast.LENGTH_SHORT).show();
            return result;
        }

        try {
            checkDbService = new CheckDAL(this);
            String remark = edRemark.getText().toString();
            CheckModel scanResult = checkDbService.getCheckModel(tvScanResultLast.getText().toString().trim());
            //如果快速盘点，则不关心备注更新
            if (cbQuickCheck.isChecked()) {
                if (scanResult != null && scanResult.getState().trim().equals(OperateType.STATECHECKED)) {
                    Toast.makeText(this, "此资产已盘，无法再次盘点！", Toast.LENGTH_SHORT).show();
                    return result;
                }
                if (scanResult != null && scanResult.getState().trim().equals(OperateType.STATEOVERAGE)) {
                    Toast.makeText(this, "此资产已盘盈，无法再次盘点！", Toast.LENGTH_SHORT).show();
                    return result;
                }
            } else {
                if (scanResult != null && (scanResult.getState().trim().equals(OperateType.STATECHECKED) || scanResult.getState().trim().equals(OperateType.STATEOVERAGE))) {
                    if (remark == null || remark.trim().equals("")) {
                        Toast.makeText(this, "备注为空，无法更新！", Toast.LENGTH_SHORT).show();
                        return result;
                    }
                    boolean updateResult = checkDbService.updateRemark
                            (tvScanResultLast.getText().toString().trim(), remark);
                    if (updateResult) {
                        result = true;
                        Toast.makeText(this, "备注更新成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "备注更新失败！", Toast.LENGTH_SHORT).show();
                    }
                    return result;
                }
            }
            String scanState = scanResult == null || scanResult.getState().trim().equals("") ? OperateType.STATEOVERAGE : OperateType.STATECHECKED;
            CheckModel checkModel = new CheckModel();
            checkModel.setCheckCode(codeResult);
            checkModel.setState(OperateType.STATEOVERAGE);
            SharedPreferences user = getSharedPreferences("user_info", 0);
            String strName = user.getString("NAME", "");//盘点人

            checkModel.setmCheckUser(strName);
            checkModel.setmCheckMemo(remark);
            //String  strPassword=user.getString("PWD","");
            boolean checkResult = scanState.trim().equals(OperateType.STATEOVERAGE) ? checkDbService.addCheckData(checkModel) : checkDbService.saveChecked(codeResult, scanState, strName);
            result = checkResult;
            Toast.makeText(this, checkResult ? "盘点成功！" : "盘点失败！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        return result;
    }

    //更新查询结果
    private void updateDate() {
        try {
            checkDbService = new CheckDAL(this);
            CheckModel scanResult = checkDbService.getCheckModel(tvScanResultLast.getText().toString().trim());
            String showResult = "[编号]：" + scanResult.getCheckCode() + "\r\n[状态]: " + ConvertHelper.getStateName(scanResult.getState()) + "\r\n";
            if (scanResult.getRemark() != null) {
                String[] names = scanResult.getCheckName().split(SpliteCode);
                String[] msgs = scanResult.getRemark().split(SpliteCode);
                for (int i = 0; i < msgs.length; i++) {
                    showResult += "[" + names[i] + "] : " + msgs[i] + "\r\n";
                }
            }
            showResult += "[盘点人]:" + scanResult.getmCheckUser() + "\r\n";
            showResult += "[盘点时间]:" + scanResult.getmTime() + "\r\n";
            showResult += "[盘点备注]:" + scanResult.getmCheckMemo() + "\r\n";
            tvShowResultDetail.setText(showResult);
            initTitleMsg();
        } catch (Exception e) {
            tvShowResultDetail.setText("");
            Toast.makeText(this, "未查询到该资产，若盘点则为盘盈！", Toast.LENGTH_SHORT).show();
        }
        //输入框获取焦点
        edShowCodeResult.setFocusable(true);
        edShowCodeResult.requestFocus();
        edShowCodeResult.setFocusableInTouchMode(true);
    }

    private void cancelAll() {
        edShowCodeResult.setText("");
        tvScanResultLast.setText("");
        tvShowResultDetail.setText("");
    }

    //设置中间部分权重
    private void setLayoutResultMin() {
        lyResult.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, 2));
    }

    //设置中间部分权重
    private void setLayoutResultMax() {
        lyResult.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, 8));
    }

    //初始化标题栏信息
    private void initTitleMsg() {
        checkDbService = new CheckDAL(this);
        TitleMessageModel titleMsg = checkDbService.getTitleMessage();
        if (titleMsg != null) {
            String checkedCount = (titleMsg.getCheckedCount() == null || titleMsg.getCheckedCount().toString().equals("")) ? "0" : titleMsg.getCheckedCount();
            String uncheckCount = (titleMsg.getUncheckCount() == null || titleMsg.getUncheckCount().toString().equals("")) ? "0" : titleMsg.getUncheckCount();
            String overageCount = (titleMsg.getOverageCount() == null || titleMsg.getOverageCount().toString().equals("")) ? "0" : titleMsg.getOverageCount();
            tvTitleChecked.setText("已盘：" + checkedCount);
            tvTitleUncheck.setText("未盘：" + uncheckCount);
            tvTitleOverage.setText("盘盈：" + overageCount);
        }
    }

    //点击查询按钮和回车按钮的时候执行的操作
    private void searchAndEnterKey() {
        if (!edShowCodeResult.getText().toString().equals("")) {
            tvScanResultLast.setText(edShowCodeResult.getText().toString());
            edShowCodeResult.setText("");
        }
        updateDate();
        //如果勾选快速盘点，那么回车事件在查询以后，直接盘点
        if (cbQuickCheck.isChecked()){
            checkdate();
            updateDate();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        createVeoctity(event);
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (getSpeed() > 4000) {
                recycleVelocityTracker();
                finish();
            }
        }
        return true;
    }

    private void createVeoctity(MotionEvent event) {
        if (mVeloctity == null) {
            mVeloctity = VelocityTracker.obtain();
        }
        mVeloctity.addMovement(event);
    }

    private void recycleVelocityTracker() {
        mVeloctity.recycle();
        mVeloctity = null;
    }

    private int getSpeed() {
        mVeloctity.computeCurrentVelocity(1000);
        int speed = (int) mVeloctity.getXVelocity();
        return speed;
    }
}
